from flask import Blueprint, request, jsonify, current_app,g
import os

from flask_jwt_extended import jwt_required
from werkzeug.utils import secure_filename
from app.models.user import User
from app.core.extensions import db
from app.services.auth import token_required

user_bp = Blueprint('user', __name__)


@user_bp.route('/update', methods=['POST'])
@jwt_required()
def update_user():
    data = request.get_json()
    user_id = data.get('user_id')

    if not user_id:
        return jsonify({"code": 0, "msg": "缺少用户ID"})

    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({"code": 0, "msg": "用户不存在"})

        # 更新用户信息
        if 'nick_name' in data:
            user.nick_name = data['nick_name']
        if 'avatar_url' in data:
            user.avatar_url = data['avatar_url']
        if 'gender' in data:
            user.gender = data['gender']
        if 'country' in data:
            user.country = data['country']
        if 'province' in data:
            user.province = data['province']
        if 'city' in data:
            user.city = data['city']
        if 'mobile' in data:
            user.mobile = data['mobile']

        db.session.commit()

        return jsonify({
            "code": 1,
            "msg": "更新成功",
            "data": {
                "userInfo": user.to_dict()
            }
        })

    except Exception as e:
        current_app.logger.error(f"更新用户信息错误: {str(e)}")
        return jsonify({"code": 0, "msg": f"服务器错误: {str(e)}"})


@user_bp.route('/update_usage', methods=['POST'])
@jwt_required()
def update_usage():
    data = request.get_json()
    user_id = data.get('user_id')

    if not user_id:
        return jsonify({"code": 0, "msg": "缺少用户ID"})

    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({"code": 0, "msg": "用户不存在"})

        # 增加使用次数
        user.usage_count += 10  # 每次增加10次使用次数
        db.session.commit()

        return jsonify({
            "code": 1,
            "msg": "使用次数更新成功",
            "data": {
                "usage_count": user.usage_count
            }
        })

    except Exception as e:
        current_app.logger.error(f"更新使用次数错误: {str(e)}")
        return jsonify({"code": 0, "msg": f"服务器错误: {str(e)}"})


@user_bp.route('/get_usage_count', methods=['GET'])
def get_usage_count():
    user_id = request.args.get('user_id')

    if not user_id:
        return jsonify({"code": 0, "msg": "缺少用户ID"})

    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({"code": 0, "msg": "用户不存在"})

        return jsonify({
            "code": 1,
            "msg": "获取成功",
            "data": {
                "usage_count": user.usage_count
            }
        })

    except Exception as e:
        current_app.logger.error(f"获取使用次数错误: {str(e)}")
        return jsonify({"code": 0, "msg": f"服务器错误: {str(e)}"})


@user_bp.route('/profile', methods=['GET'])
def get_user_profile():
    user_id = request.args.get('user_id')

    if not user_id:
        return jsonify({"code": 0, "msg": "缺少用户ID"})

    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({"code": 0, "msg": "用户不存在"})

        return jsonify({
            "code": 1,
            "msg": "获取成功",
            "data": {
                "userInfo": user.to_dict(),
                "is_dealer": False
            }
        })

    except Exception as e:
        current_app.logger.error(f"获取用户资料错误: {str(e)}")
        return jsonify({"code": 0, "msg": f"服务器错误: {str(e)}"})


@user_bp.route('/activate_code', methods=['POST'])
@jwt_required()
def activate_code():
    from app.models.agents import ActivationCode
    # 获取用户信息和激活码
    data = request.get_json()
    user_id = data.get('user_id')
    code = (data.get('code') or '').strip()

    if not user_id or not code:
        return jsonify({"code": 0, "msg": "参数不完整"})

    # 检查用户是否存在
    user = User.query.get(user_id)
    if not user:
        return jsonify({"code": 0, "msg": "用户不存在"})
    # from sqlalchemy import text
    # sql = text("SELECT * FROM activation_codes WHERE code = :code AND tenant_id = :tenant_id")
    # params = {'code': code, 'tenant_id': g.tenant_id}
    # result = db.session.execute(sql, params)

    # 检查激活码是否存在
    activation_code = ActivationCode.query.filter_by(code=code).first()
    if not activation_code:
        return jsonify({"code": 0, "msg": "激活码不存在！"})

    # 检查激活码是否已使用
    if activation_code.status == 1:
        return jsonify({"code": 0, "msg": "激活码已被使用"})

    # 检查激活码是否过期
    import datetime

    # 增加用户使用次数
    try:
        user.usage_count += activation_code.usage_count

        # 更新激活码状态
        activation_code.status = 1
        activation_code.used_by = user_id
        activation_code.used_time = datetime.datetime.now()

        db.session.commit()

        return jsonify({
            "code": 1,
            "msg": f"激活成功，您的使用次数增加了{activation_code.usage_count}次",
            "data": {
                "usage_count": user.usage_count,
                "added_count": activation_code.usage_count
            }
        })
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"激活码使用错误: {str(e)}")
        return jsonify({"code": 0, "msg": f"激活失败: {str(e)}"})

